package com.zhentao.service.impl;

import com.zhentao.pojo.*;
import com.zhentao.service.*;
import com.zhentao.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.Calendar;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private ProductService productService;

    @Autowired
    private StockService stockService;

    @Autowired
    private AccountService accountService;

    @Autowired
    private AccountFlowService accountFlowService;

    @Autowired
    private RetailOutboundService retailOutboundService;

    @Autowired
    private RetailOutboundItemService retailOutboundItemService;

    @Autowired
    private PurchaseOrderService purchaseOrderService;

    @Autowired
    private PurchaseOrderItemService purchaseOrderItemService;

    @Autowired
    private SalesOrderService salesOrderService;

    @Autowired
    private SalesOrderItemService salesOrderItemService;

    @Autowired
    private StockMovementService stockMovementService;

    @Autowired
    private StockWarningService stockWarningService;

    @Autowired
    private ProductCategoryService productCategoryService;

    @Autowired
    private WarehouseService warehouseService;

    @Override
    public List<ProductStockReportVO> getProductStockReport() {
        try {
            List<ProductStockReportVO> result = new ArrayList<>();

            // 获取所有商品
            List<Product> products = productService.list();
            if (products == null || products.isEmpty()) {
                return getMockProductStockData();
            }

            // 获取所有库存
            List<Stock> stocks = stockService.list();
            if (stocks == null) {
                stocks = new ArrayList<>();
            }

            // 获取所有商品分类
            List<ProductCategory> categories = productCategoryService.list();
            Map<Long, String> categoryMap = new HashMap<>();
            if (categories != null) {
                categoryMap = categories.stream()
                        .collect(Collectors.toMap(ProductCategory::getId, ProductCategory::getName, (k1, k2) -> k1));
            }

            // 按商品分组统计库存
            Map<Long, List<Stock>> stockMap = stocks.stream()
                    .collect(Collectors.groupingBy(Stock::getProductId));

            for (Product product : products) {
                ProductStockReportVO vo = new ProductStockReportVO();
                vo.setProductId(product.getId());
                vo.setProductName(product.getName());
                vo.setCategoryName(categoryMap.getOrDefault(product.getCategoryId(), "未分类"));

                List<Stock> productStocks = stockMap.get(product.getId());
                if (productStocks != null && !productStocks.isEmpty()) {
                    // 计算总库存
                    int totalStock = productStocks.stream()
                            .mapToInt(stock -> stock.getQuantity() != null ? stock.getQuantity().intValue() : 0)
                            .sum();
                    vo.setTotalStock(totalStock);

                    // 计算总金额
                    BigDecimal totalAmount = productStocks.stream()
                            .map(stock -> {
                                BigDecimal price = stock.getUnitPrice() != null ? stock.getUnitPrice() : BigDecimal.ZERO;
                                BigDecimal qty = stock.getQuantity() != null ? stock.getQuantity() : BigDecimal.ZERO;
                                return price.multiply(qty);
                            })
                            .reduce(BigDecimal.ZERO, BigDecimal::add);
                    vo.setTotalAmount(totalAmount);

                    // 设置仓库数量
                    vo.setWarehouseCount(productStocks.size());
                } else {
                    vo.setTotalStock(0);
                    vo.setTotalAmount(BigDecimal.ZERO);
                    vo.setWarehouseCount(0);
                }

                result.add(vo);
            }

            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return getMockProductStockData();
        }
    }

    @Override
    public List<AccountReportVO> getAccountReport() {
        try {
            List<AccountReportVO> result = new ArrayList<>();

            // 获取所有账户
            List<Account> accounts = accountService.list();
            if (accounts == null || accounts.isEmpty()) {
                return getMockAccountData();
            }

            // 获取账户流水
            List<AccountFlow> flows = accountFlowService.list();
            if (flows == null) {
                flows = new ArrayList<>();
            }

            // 按账户分组统计流水
            Map<Long, List<AccountFlow>> flowMap = flows.stream()
                    .collect(Collectors.groupingBy(AccountFlow::getAccountId));

            for (Account account : accounts) {
                AccountReportVO vo = new AccountReportVO();
                vo.setAccountId(account.getId());
                vo.setAccountName(account.getName());
                vo.setAccountType(account.getType() != null ? account.getType() : "未知");
                vo.setBalance(account.getCurrentAmount() != null ? account.getCurrentAmount() : BigDecimal.ZERO);

                List<AccountFlow> accountFlows = flowMap.get(account.getId());
                if (accountFlows != null && !accountFlows.isEmpty()) {
                    // 计算本月收入 (flowType为"收入"或"IN")
                    BigDecimal monthlyIncome = accountFlows.stream()
                            .filter(flow -> ("收入".equals(flow.getFlowType()) || "IN".equals(flow.getFlowType())) && isCurrentMonth(flow.getCreateTime()))
                            .map(AccountFlow::getAmount)
                            .filter(Objects::nonNull)
                            .reduce(BigDecimal.ZERO, BigDecimal::add);
                    vo.setMonthlyIncome(monthlyIncome);

                    // 计算本月支出 (flowType为"支出"或"OUT")
                    BigDecimal monthlyExpense = accountFlows.stream()
                            .filter(flow -> ("支出".equals(flow.getFlowType()) || "OUT".equals(flow.getFlowType())) && isCurrentMonth(flow.getCreateTime()))
                            .map(AccountFlow::getAmount)
                            .filter(Objects::nonNull)
                            .reduce(BigDecimal.ZERO, BigDecimal::add);
                    vo.setMonthlyExpense(monthlyExpense);

                    // 计算交易次数
                    vo.setTransactionCount(accountFlows.size());
                } else {
                    vo.setMonthlyIncome(BigDecimal.ZERO);
                    vo.setMonthlyExpense(BigDecimal.ZERO);
                    vo.setTransactionCount(0);
                }

                result.add(vo);
            }

            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return getMockAccountData();
        }
    }

    @Override
    public List<RetailReportVO> getRetailReport() {
        try {
            List<RetailReportVO> result = new ArrayList<>();

            // 获取零售出库记录
            List<RetailOutbound> outbounds = retailOutboundService.list();
            if (outbounds == null || outbounds.isEmpty()) {
                return getMockRetailData();
            }

            List<RetailOutboundItem> items = retailOutboundItemService.list();
            if (items == null) {
                items = new ArrayList<>();
            }

            // 按日期分组统计
            Map<String, List<RetailOutbound>> dateMap = outbounds.stream()
                    .filter(outbound -> outbound.getOutboundDate() != null)
                    .collect(Collectors.groupingBy(outbound ->
                            outbound.getOutboundDate().toString().substring(0, 10)));

            for (Map.Entry<String, List<RetailOutbound>> entry : dateMap.entrySet()) {
                String date = entry.getKey();
                List<RetailOutbound> dayOutbounds = entry.getValue();

                RetailReportVO vo = new RetailReportVO();
                vo.setDate(date);
                vo.setOrderCount(dayOutbounds.size());

                // 计算总金额和总数量
                BigDecimal totalAmount = BigDecimal.ZERO;
                int totalQuantity = 0;

                for (RetailOutbound outbound : dayOutbounds) {
                    List<RetailOutboundItem> outboundItems = items.stream()
                            .filter(item -> item.getOutboundId() != null && item.getOutboundId().equals(outbound.getId()))
                            .collect(Collectors.toList());

                    for (RetailOutboundItem item : outboundItems) {
                        BigDecimal price = item.getUnitPrice() != null ? item.getUnitPrice() : BigDecimal.ZERO;
                        BigDecimal qty = item.getQuantity() != null ? item.getQuantity() : BigDecimal.ZERO;
                        totalAmount = totalAmount.add(price.multiply(qty));
                        totalQuantity += qty.intValue();
                    }
                }

                vo.setTotalAmount(totalAmount);
                vo.setTotalQuantity(totalQuantity);

                result.add(vo);
            }

            // 按日期排序
            result.sort(Comparator.comparing(RetailReportVO::getDate));

            return result.isEmpty() ? getMockRetailData() : result;
        } catch (Exception e) {
            e.printStackTrace();
            return getMockRetailData();
        }
    }

    @Override
    public List<PurchaseReportVO> getPurchaseReport() {
        try {
            List<PurchaseReportVO> result = new ArrayList<>();

            // 获取采购订单
            List<PurchaseOrder> orders = purchaseOrderService.list();
            if (orders == null || orders.isEmpty()) {
                return getMockPurchaseData();
            }

            List<PurchaseOrderItem> items = purchaseOrderItemService.list();
            if (items == null) {
                items = new ArrayList<>();
            }

            // 按日期分组统计
            Map<String, List<PurchaseOrder>> dateMap = orders.stream()
                    .filter(order -> order.getOrderDate() != null)
                    .collect(Collectors.groupingBy(order ->
                            order.getOrderDate().toString().substring(0, 10)));

            for (Map.Entry<String, List<PurchaseOrder>> entry : dateMap.entrySet()) {
                String date = entry.getKey();
                List<PurchaseOrder> dayOrders = entry.getValue();

                PurchaseReportVO vo = new PurchaseReportVO();
                vo.setDate(date);
                vo.setOrderCount(dayOrders.size());

                // 计算总金额和总数量
                BigDecimal totalAmount = BigDecimal.ZERO;
                int totalQuantity = 0;

                for (PurchaseOrder order : dayOrders) {
                    List<PurchaseOrderItem> orderItems = items.stream()
                            .filter(item -> item.getOrderId() != null && item.getOrderId().equals(order.getId()))
                            .collect(Collectors.toList());

                    for (PurchaseOrderItem item : orderItems) {
                        BigDecimal price = item.getUnitPrice() != null ? item.getUnitPrice() : BigDecimal.ZERO;
                        BigDecimal qty = item.getQuantity() != null ? item.getQuantity() : BigDecimal.ZERO;
                        totalAmount = totalAmount.add(price.multiply(qty));
                        totalQuantity += qty.intValue();
                    }
                }

                vo.setTotalAmount(totalAmount);
                vo.setTotalQuantity(totalQuantity);

                result.add(vo);
            }

            // 按日期排序
            result.sort(Comparator.comparing(PurchaseReportVO::getDate));

            return result.isEmpty() ? getMockPurchaseData() : result;
        } catch (Exception e) {
            e.printStackTrace();
            return getMockPurchaseData();
        }
    }

    @Override
    public List<SaleReportVO> getSaleReport() {
        try {
            List<SaleReportVO> result = new ArrayList<>();

            // 获取销售订单
            List<SalesOrder> orders = salesOrderService.list();
            if (orders == null || orders.isEmpty()) {
                return getMockSaleData();
            }

            List<SalesOrderItem> items = salesOrderItemService.list();
            if (items == null) {
                items = new ArrayList<>();
            }

            // 按日期分组统计
            Map<String, List<SalesOrder>> dateMap = orders.stream()
                    .filter(order -> order.getOrderDate() != null)
                    .collect(Collectors.groupingBy(order ->
                            order.getOrderDate().toString().substring(0, 10)));

            for (Map.Entry<String, List<SalesOrder>> entry : dateMap.entrySet()) {
                String date = entry.getKey();
                List<SalesOrder> dayOrders = entry.getValue();

                SaleReportVO vo = new SaleReportVO();
                vo.setDate(date);
                vo.setOrderCount(dayOrders.size());

                // 计算总金额和总数量
                BigDecimal totalAmount = BigDecimal.ZERO;
                int totalQuantity = 0;

                for (SalesOrder order : dayOrders) {
                    List<SalesOrderItem> orderItems = items.stream()
                            .filter(item -> item.getOrderId() != null && item.getOrderId().equals(order.getId()))
                            .collect(Collectors.toList());

                    for (SalesOrderItem item : orderItems) {
                        BigDecimal price = item.getUnitPrice() != null ? item.getUnitPrice() : BigDecimal.ZERO;
                        BigDecimal qty = item.getQuantity() != null ? item.getQuantity() : BigDecimal.ZERO;
                        totalAmount = totalAmount.add(price.multiply(qty));
                        totalQuantity += qty.intValue();
                    }
                }

                vo.setTotalAmount(totalAmount);
                vo.setTotalQuantity(totalQuantity);

                result.add(vo);
            }

            // 按日期排序
            result.sort(Comparator.comparing(SaleReportVO::getDate));

            return result.isEmpty() ? getMockSaleData() : result;
        } catch (Exception e) {
            e.printStackTrace();
            return getMockSaleData();
        }
    }

    @Override
    public List<InventoryFlowReportVO> getInventoryFlowReport() {
        try {
            List<InventoryFlowReportVO> result = new ArrayList<>();

            // 获取库存流水
            List<StockMovement> movements = stockMovementService.list();
            if (movements == null || movements.isEmpty()) {
                return getMockInventoryFlowData();
            }

            // 按日期分组统计
            Map<String, List<StockMovement>> dateMap = movements.stream()
                    .filter(movement -> movement.getCreateTime() != null)
                    .collect(Collectors.groupingBy(movement ->
                            movement.getCreateTime().toString().substring(0, 10)));

            for (Map.Entry<String, List<StockMovement>> entry : dateMap.entrySet()) {
                String date = entry.getKey();
                List<StockMovement> dayMovements = entry.getValue();

                InventoryFlowReportVO vo = new InventoryFlowReportVO();
                vo.setDate(date);

                // 统计入库和出库
                int inQuantity = 0;
                int outQuantity = 0;
                BigDecimal inAmount = BigDecimal.ZERO;
                BigDecimal outAmount = BigDecimal.ZERO;

                for (StockMovement movement : dayMovements) {
                    if ("IN".equals(movement.getMovementType()) || "入库".equals(movement.getMovementType())) { // 入库
                        inQuantity += movement.getQuantity() != null ? movement.getQuantity().intValue() : 0;
                        BigDecimal price = movement.getUnitPrice() != null ? movement.getUnitPrice() : BigDecimal.ZERO;
                        BigDecimal qty = movement.getQuantity() != null ? movement.getQuantity() : BigDecimal.ZERO;
                        inAmount = inAmount.add(price.multiply(qty));
                    } else if ("OUT".equals(movement.getMovementType()) || "出库".equals(movement.getMovementType())) { // 出库
                        outQuantity += movement.getQuantity() != null ? movement.getQuantity().intValue() : 0;
                        BigDecimal price = movement.getUnitPrice() != null ? movement.getUnitPrice() : BigDecimal.ZERO;
                        BigDecimal qty = movement.getQuantity() != null ? movement.getQuantity() : BigDecimal.ZERO;
                        outAmount = outAmount.add(price.multiply(qty));
                    }
                }

                vo.setInQuantity(inQuantity);
                vo.setOutQuantity(outQuantity);
                vo.setInAmount(inAmount);
                vo.setOutAmount(outAmount);
                vo.setNetQuantity(inQuantity - outQuantity);
                vo.setNetAmount(inAmount.subtract(outAmount));

                result.add(vo);
            }

            // 按日期排序
            result.sort(Comparator.comparing(InventoryFlowReportVO::getDate));

            return result.isEmpty() ? getMockInventoryFlowData() : result;
        } catch (Exception e) {
            e.printStackTrace();
            return getMockInventoryFlowData();
        }
    }

    @Override
    public List<StockWarningVO> getStockWarning() {
        try {
            List<StockWarningVO> result = new ArrayList<>();

            // 获取库存预警记录
            List<StockWarning> warnings = stockWarningService.list();
            if (warnings == null || warnings.isEmpty()) {
                return getMockStockWarningData();
            }

            // 获取所有产品信息
            List<Product> products = productService.list();
            Map<Long, Product> productMap = products.stream()
                    .collect(Collectors.toMap(Product::getId, product -> product, (k1, k2) -> k1));

            // 获取所有仓库信息
            List<Warehouse> warehouses = warehouseService.list();
            Map<Long, Warehouse> warehouseMap = warehouses.stream()
                    .collect(Collectors.toMap(Warehouse::getId, warehouse -> warehouse, (k1, k2) -> k1));

            for (StockWarning warning : warnings) {
                StockWarningVO vo = new StockWarningVO();
                vo.setProductId(warning.getProductId());

                // 获取产品名称
                Product product = productMap.get(warning.getProductId());
                vo.setProductName(product != null ? product.getName() : "未知产品");

                vo.setWarehouseId(warning.getWarehouseId());

                // 获取仓库名称
                Warehouse warehouse = warehouseMap.get(warning.getWarehouseId());
                vo.setWarehouseName(warehouse != null ? warehouse.getName() : "未知仓库");

                // 获取当前库存数量（从Stock表查询）
                List<Stock> stocks = stockService.list();
                Stock productStock = stocks.stream()
                        .filter(stock -> stock.getProductId().equals(warning.getProductId()) &&
                                       stock.getWarehouseId().equals(warning.getWarehouseId()))
                        .findFirst()
                        .orElse(null);

                vo.setCurrentStock(productStock != null && productStock.getQuantity() != null ?
                        productStock.getQuantity().intValue() : 0);
                vo.setMinStock(warning.getMinStock() != null ? warning.getMinStock().intValue() : 0);
                vo.setMaxStock(warning.getMaxStock() != null ? warning.getMaxStock().intValue() : 0);

                // 根据当前库存和预警阈值判断预警类型
                if (productStock != null && productStock.getQuantity() != null) {
                    if (productStock.getQuantity().compareTo(warning.getMinStock()) < 0) {
                        vo.setWarningType("库存不足");
                    } else if (productStock.getQuantity().compareTo(warning.getMaxStock()) > 0) {
                        vo.setWarningType("库存积压");
                    } else {
                        vo.setWarningType("正常");
                    }
                } else {
                    vo.setWarningType("无库存信息");
                }

                vo.setWarningDate(warning.getCreateTime());

                result.add(vo);
            }

            return result.isEmpty() ? getMockStockWarningData() : result;
        } catch (Exception e) {
            e.printStackTrace();
            return getMockStockWarningData();
        }
    }

    // 辅助方法：判断是否为当前月份
    private boolean isCurrentMonth(Date date) {
        if (date == null) return false;
        Calendar cal1 = Calendar.getInstance();
        Calendar cal2 = Calendar.getInstance();
        cal1.setTime(new Date());
        cal2.setTime(date);
        return cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) &&
               cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH);
    }

    // 备用模拟数据方法
    private List<ProductStockReportVO> getMockProductStockData() {
        List<ProductStockReportVO> result = new ArrayList<>();
        for (int i = 1; i <= 10; i++) {
            ProductStockReportVO vo = new ProductStockReportVO();
            vo.setProductId((long) i);
            vo.setProductName("商品-" + i);
            vo.setCategoryName("分类-" + (i % 3 + 1));
            vo.setTotalStock(100 + i * 20);
            vo.setTotalAmount(new BigDecimal(1000 + i * 200));
            vo.setWarehouseCount(i % 3 + 1);
            result.add(vo);
        }
        return result;
    }

    private List<AccountReportVO> getMockAccountData() {
        List<AccountReportVO> result = new ArrayList<>();
        String[] accountTypes = {"现金账户", "银行账户", "支付宝", "微信"};
        for (int i = 1; i <= 4; i++) {
            AccountReportVO vo = new AccountReportVO();
            vo.setAccountId((long) i);
            vo.setAccountName(accountTypes[i - 1]);
            vo.setAccountType(String.valueOf(i));
            vo.setBalance(new BigDecimal(10000 + i * 5000));
            vo.setMonthlyIncome(new BigDecimal(2000 + i * 500));
            vo.setMonthlyExpense(new BigDecimal(1000 + i * 300));
            vo.setTransactionCount(10 + i * 5);
            result.add(vo);
        }
        return result;
    }

    private List<RetailReportVO> getMockRetailData() {
        List<RetailReportVO> result = new ArrayList<>();
        for (int i = 1; i <= 7; i++) {
            RetailReportVO vo = new RetailReportVO();
            vo.setDate("2025-01-" + String.format("%02d", i));
            vo.setOrderCount(5 + i * 2);
            vo.setTotalAmount(new BigDecimal(5000 + i * 1000));
            vo.setTotalQuantity(20 + i * 5);
            result.add(vo);
        }
        return result;
    }

    private List<PurchaseReportVO> getMockPurchaseData() {
        List<PurchaseReportVO> result = new ArrayList<>();
        for (int i = 1; i <= 7; i++) {
            PurchaseReportVO vo = new PurchaseReportVO();
            vo.setDate("2025-01-" + String.format("%02d", i));
            vo.setOrderCount(3 + i);
            vo.setTotalAmount(new BigDecimal(8000 + i * 1500));
            vo.setTotalQuantity(50 + i * 10);
            result.add(vo);
        }
        return result;
    }

    private List<SaleReportVO> getMockSaleData() {
        List<SaleReportVO> result = new ArrayList<>();
        for (int i = 1; i <= 7; i++) {
            SaleReportVO vo = new SaleReportVO();
            vo.setDate("2025-01-" + String.format("%02d", i));
            vo.setOrderCount(8 + i * 3);
            vo.setTotalAmount(new BigDecimal(12000 + i * 2000));
            vo.setTotalQuantity(30 + i * 8);
            result.add(vo);
        }
        return result;
    }

    private List<InventoryFlowReportVO> getMockInventoryFlowData() {
        List<InventoryFlowReportVO> result = new ArrayList<>();
        for (int i = 1; i <= 7; i++) {
            InventoryFlowReportVO vo = new InventoryFlowReportVO();
            vo.setDate("2025-01-" + String.format("%02d", i));
            vo.setInQuantity(100 + i * 20);
            vo.setOutQuantity(80 + i * 15);
            vo.setInAmount(new BigDecimal(5000 + i * 1000));
            vo.setOutAmount(new BigDecimal(4000 + i * 800));
            vo.setNetQuantity(20 + i * 5);
            vo.setNetAmount(new BigDecimal(1000 + i * 200));
            result.add(vo);
        }
        return result;
    }

    private List<StockWarningVO> getMockStockWarningData() {
        List<StockWarningVO> result = new ArrayList<>();
        for (int i = 1; i <= 5; i++) {
            StockWarningVO vo = new StockWarningVO();
            vo.setProductId((long) i);
            vo.setProductName("预警商品-" + i);
            vo.setWarehouseId((long) (i % 3 + 1));
            vo.setWarehouseName("仓库-" + (i % 3 + 1));
            vo.setCurrentStock(5 + i);
            vo.setMinStock(20);
            vo.setMaxStock(100);
            vo.setWarningType(i % 2 == 0 ? "库存不足" : "库存积压");
            vo.setWarningDate(new Date());
            result.add(vo);
        }
        return result;
    }

    // ==================== 新增的报表方法实现 ====================

    @Override
    public List<Map<String, Object>> getSalesProfitReport() {
        try {
            List<Map<String, Object>> result = new ArrayList<>();
            
            // 模拟销售利润数据
            for (int i = 1; i <= 7; i++) {
                Map<String, Object> row = new HashMap<>();
                row.put("date", "2025-08-" + String.format("%02d", i));
                row.put("productName", "产品-" + i);
                row.put("customerName", "客户-" + i);
                
                int income = 1000 * i;
                int cost = 700 * i;
                int profit = income - cost;
                
                row.put("income", income);
                row.put("cost", cost);
                row.put("profit", profit);
                row.put("salesAmount", income);
                row.put("salesQuantity", i * 10);
                
                result.add(row);
            }
            return result;
        } catch (Exception e) {
            return new ArrayList<>();
        }
    }

    @Override
    public List<Map<String, Object>> getSalesRankReport() {
        try {
            List<Map<String, Object>> result = new ArrayList<>();
            
            // 模拟销售排行数据
            for (int i = 10; i >= 1; i--) {
                Map<String, Object> row = new HashMap<>();
                row.put("rank", i);
                row.put("productName", "热销商品-" + i);
                row.put("productCode", "SP" + String.format("%03d", i));
                row.put("categoryName", "分类-" + ((i % 3) + 1));
                row.put("salesAmount", i * 1200);
                row.put("salesQuantity", i * 30);
                row.put("totalAmount", i * 1200);
                row.put("orderCount", i * 5);
                row.put("customerCount", i * 2);
                
                result.add(row);
            }
            return result;
        } catch (Exception e) {
            return new ArrayList<>();
        }
    }

    @Override
    public List<Map<String, Object>> getSalesRatioReport() {
        try {
            List<Map<String, Object>> result = new ArrayList<>();
            
            // 模拟销售比例数据
            String[] categories = {"电器", "服装", "食品", "家居", "其他"};
            int[] values = {35, 25, 15, 18, 7};
            
            for (int i = 0; i < categories.length; i++) {
                Map<String, Object> row = new HashMap<>();
                row.put("categoryName", categories[i]);
                row.put("percentage", values[i]);
                row.put("value", values[i]);
                row.put("salesAmount", values[i] * 1000);
                row.put("salesQuantity", values[i] * 10);
                
                result.add(row);
            }
            return result;
        } catch (Exception e) {
            return new ArrayList<>();
        }
    }

    @Override
    public List<Map<String, Object>> getNegativeStockReport() {
        try {
            List<Map<String, Object>> result = new ArrayList<>();
            
            // 模拟负库存数据
            for (int i = 1; i <= 5; i++) {
                Map<String, Object> row = new HashMap<>();
                row.put("productName", "负库存商品-" + i);
                row.put("productCode", "FK" + String.format("%03d", i));
                row.put("categoryName", "分类-" + ((i % 3) + 1));
                row.put("currentStock", -i * 3);
                row.put("committedStock", i * 5);
                row.put("availableStock", -i * 8);
                row.put("negativeStock", i * 3);
                row.put("unitPrice", 100 + i * 20);
                row.put("stockAmount", -i * 300);
                row.put("unit", "个");
                row.put("warehouseName", "仓库-" + ((i % 3) + 1));
                row.put("location", "A区-" + i);
                
                result.add(row);
            }
            return result;
        } catch (Exception e) {
            return new ArrayList<>();
        }
    }

    @Override
    public List<Map<String, Object>> getMultiAttrStockReport() {
        try {
            List<Map<String, Object>> result = new ArrayList<>();
            
            // 模拟多属性库存数据
            String[] colors = {"红色", "蓝色", "黑色", "白色"};
            String[] sizes = {"S", "M", "L", "XL"};
            String[] styles = {"经典", "时尚", "简约"};
            String[] materials = {"棉质", "涤纶", "丝绸"};
            
            for (String color : colors) {
                for (String size : sizes) {
                    for (String style : styles) {
                        Map<String, Object> row = new HashMap<>();
                        row.put("productName", "T恤-" + style);
                        row.put("productCode", "TS" + color.substring(0, 1) + size);
                        row.put("categoryName", "服装");
                        row.put("color", color);
                        row.put("size", size);
                        row.put("style", style);
                        row.put("material", materials[new Random().nextInt(materials.length)]);
                        row.put("stockQuantity", new Random().nextInt(100) + 10);
                        row.put("stockAmount", new Random().nextInt(5000) + 500);
                        row.put("unitPrice", 50 + new Random().nextInt(100));
                        row.put("unit", "件");
                        row.put("warehouseName", "主仓库");
                        row.put("location", "A区");
                        row.put("minStock", 20);
                        row.put("maxStock", 200);
                        
                        result.add(row);
                    }
                }
            }
            return result;
        } catch (Exception e) {
            return new ArrayList<>();
        }
    }

    @Override
    public List<Map<String, Object>> getPerformanceReport() {
        try {
            List<Map<String, Object>> result = new ArrayList<>();
            
            // 模拟绩效数据
            String[] employees = {"张三", "李四", "王五", "赵六", "钱七", "孙八", "周九"};
            String[] departments = {"销售部", "市场部", "客服部"};
            
            for (int i = 0; i < employees.length; i++) {
                Map<String, Object> row = new HashMap<>();
                row.put("employeeName", employees[i]);
                row.put("employeeCode", "EMP" + String.format("%03d", i + 1));
                row.put("departmentName", departments[i % departments.length]);
                row.put("position", "销售专员");
                row.put("salesAmount", 5000 + i * 3500);
                row.put("orderCount", 10 + i * 2);
                row.put("customerCount", 5 + i);
                row.put("performanceScore", 80 + i * 3);
                row.put("targetAmount", 8000);
                row.put("completionRate", (80 + i * 3) + "%");
                row.put("bonus", 500 + i * 100);
                row.put("month", "8月");
                row.put("year", "2025");
                
                result.add(row);
            }
            return result;
        } catch (Exception e) {
            return new ArrayList<>();
        }
    }
}
